package com.moniteach.server.servlet;

import java.io.IOException;
import java.sql.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;

import com.moniteach.server.db.bo.Message;
import com.moniteach.server.db.connector.PMF;
import com.moniteach.utils.Resource;

public class MessageServlet extends CommonServlet {

	private String id;
	private String theme;
	private String text;
	private String dateCreate;
	private String read;
	private String type;
	private String sender;
	private String receiver;
	private String dateRead;

	@Override
	protected void prepare(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("UTF-8");

		String action = req.getParameter(Resource.Const.action);
		if ("".equals(action) || action == null) {
			resp.getWriter().print(Resource.Const.no);
			return;
		}

		id = req.getParameter(Resource.Const.id);
		theme = req.getParameter(Resource.Const.theme);
		text = req.getParameter(Resource.Const.text);
		dateCreate = req.getParameter(Resource.Const.dateCreate);
		read = req.getParameter(Resource.Const.read);
		type = req.getParameter(Resource.Const.type);
		sender = req.getParameter(Resource.Const.sender);
		receiver = req.getParameter(Resource.Const.receiver);
		dateRead = req.getParameter(Resource.Const.dateRead);

		String response = "";
		if (Resource.Action.CREATE.equals(action)) {
			response = create();
		} else if (Resource.Action.GET_BY_ID.equals(action)) {
			response = getById();
		} else if (Resource.Action.INBOX.equals(action)) {
			response = inbox();
		} else if (Resource.Action.OUTBOX.equals(action)) {
			response = outbox();
		} else if (Resource.Action.MODIFY.equals(action)) {
			response = modify();
		}
		resp.getWriter().print(response);
	}

	@Override
	protected String create() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Date dateCreateDate = null;
			// Date dateCreateDate = Date.valueOf(dateCreate);
			Date dateReadDate = null;
			// Date dateReadDate = Date.valueOf(dateRead);
			Boolean readBoolean = false;
			// Boolean readBoolean = Boolean.valueOf(read);
			Long senderLong = Long.valueOf(sender);
			Long receiverLong = Long.valueOf(receiver);
			Message oneMessage = new Message(theme, text, type, dateCreateDate,
					senderLong, receiverLong, readBoolean, dateReadDate);
			pm.makePersistent(oneMessage);
			return String.valueOf(oneMessage.getId());
		} catch (Exception e) {
			return Resource.Const.no + e;
		} finally {
			pm.close();
		}

	}

	@Override
	protected String get() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected String getById() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Long idLong = Long.valueOf(id);
			Message entityMessage = pm.getObjectById(Message.class, idLong);
			entityMessage.toJSONObject();
			return entityMessage.toJSONObject().toString();
		} catch (Exception e) {
			return Resource.Const.no;
		} finally {
			pm.close();
		}
	}

	@Override
	protected String getAll() {
		return null;
	}

	@Override
	protected String modify() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Date dateCreateDate = null;
			// Date dateCreateDate = Date.valueOf(dateCreate);
			Date dateReadDate = null;
			// Date dateReadDate = Date.valueOf(dateRead);
			Boolean readBoolean = false;
			// Boolean readBoolean = Boolean.valueOf(read);
			Long senderLong = Long.valueOf(sender);
			Long receiverLong = Long.valueOf(receiver);
			Message oneMessage = new Message(theme, text, type, dateCreateDate,
					senderLong, receiverLong, readBoolean, dateReadDate);
			return String.valueOf(oneMessage.getId());
		} catch (Exception e) {
			return Resource.Const.no;
		} finally {
			pm.close();
		}
	}

	private String inbox() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Message.class);
		try {
			query.setFilter(String.format(
					"receiver == %1$s && type == 'one' && read == false",
					receiver));
			List<Message> results = (List<Message>) query.execute();
			if (!results.isEmpty()) {
				JSONArray objectsArray = new JSONArray();
				for (Message message : results) {
					objectsArray.put(message.toJSONObject());
				}
				return objectsArray.toString();
			} else {
				return Resource.Const.no;
			}
		} catch (Exception e) {
			return Resource.Const.no;
		} finally {
			pm.close();
		}
	}

	private String outbox() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Message.class);
		try {
			query.setFilter(String.format(
					"sender == %1$s && type == 'one' && read == false", sender));
			List<Message> results = (List<Message>) query.execute();
			if (!results.isEmpty()) {
				JSONArray objectsArray = new JSONArray();
				for (Message message : results) {
					objectsArray.put(message.toJSONObject());
				}
				return objectsArray.toString();
			} else {
				return Resource.Const.no;
			}
		} catch (Exception e) {
			return Resource.Const.no;
		} finally {
			pm.close();
		}
	}

}
